package com.kinyx.examples.services.impl;

import java.util.BitSet;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.kinyx.examples.entities.impl.BitSetUserType01Entity;
import com.kinyx.framework.enums.impl.ErrorCodeX;
import com.kinyx.framework.exception.KRuntimeException;

@Service
public class BitSetUserType01Service {

	private static final BitSet BIT_SET = BitSet.valueOf(new long[]{
			1, 2, 3
	});

	@Autowired
	private SessionFactory sessionFactory;

	public void persist() {
		final Session session = this.sessionFactory.openSession();
		session.beginTransaction();
		final BitSetUserType01Entity entity = new BitSetUserType01Entity();
		entity.setBitSet(BIT_SET);
		session.persist(entity);
		System.out.println(entity);
		session.getTransaction().commit();
		session.close();
	}

	public void check() {
		final Session session = this.sessionFactory.openSession();
		session.createQuery("from " + BitSetUserType01Entity.class.getSimpleName(), BitSetUserType01Entity.class).getResultList().forEach(entity -> {
			System.out.println(entity);
			if (!BIT_SET.equals(entity.getBitSet())) { throw new KRuntimeException(ErrorCodeX.NeverHappens); }
		});
		session.close();
	}

	public void clear() {
		final Session session = this.sessionFactory.openSession();
		session.beginTransaction();
		session.createQuery("delete from " + BitSetUserType01Entity.class.getSimpleName()).executeUpdate();
		session.getTransaction().commit();
		session.close();
	}

}
